﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Subtle.Areas.Administration.ViewModels;
using Subtle.Extensions;
using Subtle.Data.Extensions;
using Subtle.Domain.Services.Interfaces;
using Subtle.Domain.Models;
using Subtle.Controllers;

namespace Subtle.Areas.Administration.Controllers
{
	[Authorize]
    public class PostController : BaseController
    {
		private IPostService postService;
		private IUserService userService;

		/// <summary>
		/// Initializes a new Account Controller
		/// </summary>
		/// <param name="userService"></param>
		/// <param name="postService"></param>
		public PostController(IPostService postService, IUserService userService)
		{
			this.postService = postService;
			this.userService = userService;
		}

		/// <summary>
		/// Administration/Post/Index
		/// </summary>
		/// <returns></returns>
        public ActionResult Index()
        {
			IList<PostViewModel> homePostViewModels = (from archivedPost in postService.GetLatestPublishedPosts(20)
														   select PostViewModel.GetModel(archivedPost)).ToList<PostViewModel>();
			return View(homePostViewModels);
        }

		/// <summary>
		/// Administration/Post/Add
		/// </summary>
		/// <returns></returns>
		public ActionResult Add()
		{
			return View();
		}

		/// <summary>
		/// Add Post
		/// </summary>
		/// <param name="addPostViewModel"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Add(AddPostViewModel addPostViewModel)
		{
			if (ModelState.IsValid)
			{
				Post post = addPostViewModel.GetPost();

				post.User = userService.GetUser(GetUsername());
				post.SanitizedTitle = post.Title.Sanitize();
				postService.SavePost(post);
			}
			return RedirectToAction("Index", "Post");
		}

		/// <summary>
		/// Administration/Post/Edit/{id}
		/// </summary>
		/// <returns></returns>
		public ActionResult Edit(int id)
		{
			return View(EditPostViewModel.GetModel(postService.GetPost(id)));
		}

		/// <summary>
		/// Edit Post
		/// </summary>
		/// <param name="editPostViewModel"></param>
		/// <returns></returns>
		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Edit(EditPostViewModel editPostViewModel)
		{
			if (ModelState.IsValid)
			{
				Post post = editPostViewModel.GetPost();

				post.User = userService.GetUser(GetUsername());
				post.SanitizedTitle = post.Title.Sanitize();

				//ToDo : Notification if the post failed to save
				postService.SavePost(post);
			}
			return RedirectToAction("Index", "Post");
		}

		/// <summary>
		/// Administration/Post/Delete/{id}
		/// </summary>
		/// <returns></returns>
		public ActionResult Delete(int id)
		{
			//ToDo : Notification if the post failed to delete
			postService.DeletePost(postService.GetPost(id));
			return RedirectToAction("Index", "Post");
		}
    }
}
